<template>
  <div id="wrap">
    <div id="chart-wrap">
      <div>
        <div id="chart-palette"></div>
        <!-- <el-button id="submit" type="primary" @click="onSubmit">
          <span>查看</span>
        </el-button> -->
      </div>
      <div id="chart-diagram"></div>
    </div>
  </div>
</template>

<script>
import { getTechRouteTechList } from "@/api/technology";

import go from "gojs";
const MAKE = go.GraphObject.make; // 后面很多用到该变量来初始化diagram

export default {
  name: "diagram",
  // props:['diagramData'],
  props: ["val"],
  data() {
    return {
      myDiagram: "",
      diagramData: [], //流程图数据
      // currentValue:this.diagramData, //data接收转一下为方便watch监听使用
      addlist: this.val, //工艺路线表勾选的数据
      // nodeDataArray:[], //接受流程图数据的数组
      listName:[],
      linkData:[],
    };
  },
  watch: {
    // 监听父组件的modelData数据，因为子组件是和父组件一起加载模版，所以oldValue第一次为空，需要把newValue监听到的新数据返回给页面绘图
    // diagramData(newValue, oldValue){
    //     var mySelf = this;
    //     mySelf.diagramData = newValue
    //     // 赋完数据之后调用
    //     mySelf.init();
    // },
    val() {
      this.addlist = this.val;
    }
  },
  mounted: function() {
    var mySelf = this;

    mySelf.myDiagram = MAKE(go.Diagram, "chart-diagram", {
      initialContentAlignment: go.Spot.Center, // 居中显示
      "undoManager.isEnabled": true, // 支持 Ctrl-Z 和 Ctrl-Y 操作
      "toolManager.hoverDelay": 100, //tooltip提示显示延时
      "toolManager.toolTipDuration": 10000, //tooltip持续显示时间
      //isReadOnly:true,//只读
      "grid.visible": false, //显示网格
      allowMove: true, //允许拖动
      // allowDragOut:true,
      allowDelete: true,
      allowCopy: true,
      allowClipboard: true,
      "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom, //有鼠标滚轮事件放大和缩小，而不是向上和向下滚动
      layout: MAKE(go.TreeLayout, {
        angle: 0,
        layerSpacing: 30
      })
      // model: new go.GraphLinksModel(mySelf.diagramData)
    }); //构建gojs对象
    // console.log(mySelf.myDiagram);

    mySelf.myDiagram.addDiagramListener("ObjectSingleClicked", function(e) {
      // debugger
      console.log(e.subject.part);
    });
    mySelf.myDiagram.addDiagramListener("BackgroundSingleClicked", function(e) {
      // debugger
      console.log("Double-clicked at" + e.diagram.lastInput.documentPoint);
    });

    mySelf.myDiagram.addDiagramListener("ClipboardPasted", function(e) {
      // debugger
      console.log("Pasted" + e.diagram.selection.count + "parts");
    });

    mySelf.myDiagram.linkTemplate = MAKE(
      go.Link,
      {
        curve: go.Link.Bezier
      }, // 贝塞尔曲线
      {
        routing: go.Link.Normal,
        corner: 5
      },
      MAKE(go.Shape, {
        strokeWidth: 1,
        stroke: "#0095FF"
      }),
      MAKE(go.Shape, {
        strokeWidth: 1,
        toArrow: "Triangle",
        scale: 0.8,
        fill: "#0095FF",
        stroke: "null"
      }), //箭头
      MAKE(
        go.TextBlock,
        {
          // margin:20,
          stroke: "red",
          font: "12px sans-serif",
          width: 40,
          alignment: go.Spot.BottomCenter,
          alignmentFocus: go.Spot.BottomCenter,
          wrap: go.TextBlock.WrapDesiredSize
        },
        new go.Binding("text", "linktext")
      ),
      {
        toolTip: MAKE(
          go.Adornment,
          "Auto",
          MAKE(go.Shape, {
            fill: "#FFFFCC"
          }),
          MAKE(
            go.TextBlock,
            {
              margin: 4
            },
            new go.Binding("text", "name1")
          )
        ) // end of Adornment
      }
    );

    let myModel = MAKE(go.GraphLinksModel); //也可以创建link model;需要配置myModel.linkDataArray 如下

    // let startArray = { key: 1,text: "开始",}
    // let endArray = { key: 2,text: "结束",}
    // this.currentValue.unshift(startArray)
    // this.currentValue.push(endArray)

    // myModel.nodeDataArray = [];
    myModel.nodeDataArray = [
      { key: 1, text: "开始" },
      { key: 2, text: "打印输出" },
      { key: 3, text: "生产开工" },
      { key: 4, text: "输出质检" },
      { key: 5, text: "包装" },
      { key: 6, text: "结束" }
    ];

    var lightText = "black";
    mySelf.myDiagram.nodeTemplateMap.add(
      "Next",
      MAKE(
        go.Node,
        // new go.Binding("location", "loc", go.Point.parse),
        { width: 81, height: 40, background: "#FFF" ,cursor: "pointer",locationSpot: go.Spot.Center},
        "Horizontal", //设置并定义节点模块内容布局走向:Vertical(垂直),Auto(自动),Horizontal(水平)
        // nodeStyle(),
        MAKE(
          go.Panel, //声明创建一个新的面板对象,自定义方式可参考mySelf.myDiagram.nodeTemplate
          //表明需要创建一个panel面板对象
          MAKE(
            //声明构建一个圆角矩形
            go.Shape,
            "RoundedRectangle",
            {
              width: 80,
              height: 40,
              fill: null, //模块内填充颜色
              // fromLinkable: true, toLinkable: true, cursor: 'pointer',
              stroke: "#CCC", //外填充颜色(可理解为margin,也可以当成外边框颜色来理解)
              strokeWidth: 1, //外边框(填充)宽度
              // strokeDashArray: [6, 6, 2, 2],
              angle: 0 //模块形状的偏移量(角度)
            },
            new go.Binding("figure", "figure") //声明并创建一个新的图形
          ),
          MAKE(
            //声明一个可编辑文本域
            go.TextBlock,
            {
              font: "10pt Helvetica, Arial, sans-serif",
              stroke: lightText,
              width: 80,
              height: 20,
              textAlign:"center",
              verticalAlignment: go.Spot.Center,
              maxSize: new go.Size(360, NaN),
              wrap: go.TextBlock.WrapFit, //文本域换行
              editable: true, //是否可编辑
              margin: 5,
              wrap: go.TextBlock.WrapDesiredSize
            },
            new go.Binding("text").makeTwoWay()
          )
        ),
        // four named ports, one on each side:
        makePort("T", go.Spot.Top, false, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, false)
      )
    );

    mySelf.myDiagram.nodeTemplate = MAKE(
      go.Node,
      // new go.Binding("location", "loc", go.Point.parse),
      {
        width: 81,
        height: 40,
        background: "#FFF",
        cursor: "pointer",
        locationSpot: go.Spot.Center
      },
      "Horizontal", //设置并定义节点模块内容布局走向:Vertical(垂直),Auto(自动),Horizontal(水平)
      // nodeStyle(),
      MAKE(
        go.Panel, //声明创建一个新的面板对象,自定义方式可参考mySelf.myDiagram.nodeTemplate
        //表明需要创建一个panel面板对象
        MAKE(
          //声明构建一个圆角矩形
          go.Shape,
          "RoundedRectangle",
          {
            width: 80,
            height: 40,
            fill: null, //模块内填充颜色
            fromLinkable: true,
            toLinkable: true,
            cursor: "pointer",
            stroke: "#CCC", //外填充颜色(可理解为margin,也可以当成外边框颜色来理解)
            strokeWidth: 1, //外边框(填充)宽度
            angle: 0 //模块形状的偏移量(角度)
          },
          new go.Binding("figure", "figure") //声明并创建一个新的图形
        ),
        MAKE(
          //声明一个可编辑文本域
          go.TextBlock,
          {
            font: "10pt Helvetica, Arial, sans-serif",
            stroke: lightText,
            width: 78,
            height: 30,
            textAlign:"center",
            verticalAlignment: go.Spot.Center,
            maxSize: new go.Size(360, NaN),
            wrap: go.TextBlock.WrapFit, //文本域换行
            editable: true, //是否可编辑
            margin: 5,
            wrap: go.TextBlock.WrapDesiredSize
          },
          new go.Binding("text").makeTwoWay()
        )
      ),
      makePort("T", go.Spot.Top, false, true),
      makePort("L", go.Spot.Left, true, true),
      makePort("R", go.Spot.Right, true, true),
      makePort("B", go.Spot.Bottom, true, false)
    );

    //Node连接线
    function makePort(name, spot, output, input) {
      return MAKE(go.Shape, "Circle", {
        fill: "transparent",
        margin: -10,
        stroke: null, // this is changed to "white" in the showPorts function
        desiredSize: new go.Size(10, 10),
        alignment: spot, //对齐
        alignmentFocus: spot, // align the port on the main Shape将端口与主形状对齐
        portId: name, // declare this object to be a "port"将此对象声明为端口
        fromSpot: spot,
        toSpot: spot, // declare where links may connect at this port声明链接在此端口的连接位置
        fromLinkable: output,
        toLinkable: input, // declare whether the user may draw links to/from here声明用户是否可以从此处绘制链接
        cursor: "pointer" // show a different cursor to indicate potential link point显示不同的光标以指示潜在的链接点
      });
    }
    //  linktext: "成功" 
    // myModel.nodeDataArray = mySelf.diagramData;
    myModel.linkDataArray = [
      { from: 1, to: 2 },
      { from: 2, to: 3,},
      { from: 3, to: 4,},
      { from: 4, to: 5,},
      { from: 5, to: 6 },
    ];

    mySelf.myDiagram.model = myModel;
    mySelf.init();
    mySelf.addlist = this.val;
  },
  methods: {
    init() {
      let mySelf = this;
      window.myPalette = MAKE(go.Palette, "chart-palette", {
        scrollsPageOnFocus: false,
        nodeTemplateMap: mySelf.myDiagram.nodeTemplateMap,
        model: new go.GraphLinksModel([
          {
            category: "Next",
            text: "步骤N",
            
          }
        ])
      });
    },
    //工艺路线详情
    onSubmit() {
      getTechRouteTechList({ techRouteId: this.$parent.currentData.TechRouteId }).then(
      res => {
        if (parseInt(res.Code) === 1) {
          this.diagramList = res.Result.TechList;             
          for(var i=0; i<this.diagramList.length; i++){
            for(var j=0; j<this.diagramList.length-i-1;j++){
              if(this.diagramList[j].RouteWorkOrder>this.diagramList[j+1].RouteWorkOrder){
                var temp = this.diagramList[j]
                this.diagramList[j] = this.diagramList[j+1]
                this.diagramList[j+1]=temp
              }
            }
          }
          let listName = [];   
          var key = 0;
          this.diagramList.forEach(el => {
            listName.push({text:el.Name,key:++key})
          }); 
          this.diagramData = listName;
          console.log(this.diagramData);
          let myModel = MAKE(go.GraphLinksModel); //也可以创建link model;需要配置myModel.linkDataArray 如下
          myModel.nodeDataArray = listName;

          let linklList = []
          for(var i = 0; i < this.diagramList.length; i++){
            linklList.push({from:i+1,to:i+2})
          }
          console.log(linklList)
          // myModel.nodeDataArray = mySelf.diagramData;
          myModel.linkDataArray = linklList             
          //  mySelf.myDiagram.model = myModel;

          console.log((this.myDiagram.model = myModel));
        }
      }).catch(res=>{})
    }
  }
  // }
};
</script>
<style lang="less" scoped>
#wrap {
  height: 160px;
  padding: 0 20px;
  // background-color: #ccc;
  // border: solid 1px rgb(244, 244, 244);
  #chart-wrap {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 22px;
    #chart-palette {
      width: 100px;
      height: 60px;
      // margin-top: 90px;
      margin-right: 10px;
      background-color: white;
      // border: solid 1px rgb(244, 244, 244);
    }
    #submit {
      width: 80px;
      margin-top: 5px;
      margin-left: 10px;
    }
    #chart-diagram {
      flex-grow: 1;
      height: 149px;
      background-color: white;
      // border: solid 1px rgb(244, 244, 244);
    }
  }
}

#lateEntry {
  clear: both;
  background-color: rgb(255, 255, 255);
  border: solid 1px rgb(244, 244, 244);

  > span {
    display: inline-block;
    height: 50px;
    font-size: 18px;
    line-height: 50px;
    text-indent: 30px;
    letter-spacing: 0.8px;
    text-align: left;
    color: rgb(35, 35, 35);
    // border-bottom: 1px solid rgb(234, 234, 234);
  }
}
</style>
